package com.ssly.media.manage.controller.api;

import com.ssly.media.manage.configuration.MediaProperties;
import com.ssly.media.manage.domain.ConvertTask;
import com.ssly.media.manage.domain.DownTask;
import com.ssly.media.manage.domain.SourceMedia;
import com.ssly.media.manage.ffmpeg.Media;
import com.ssly.media.manage.repository.DownTaskRepository;
import com.ssly.media.manage.service.ConvertTaskService;
import com.ssly.media.manage.service.SourceMediaService;
import com.ssly.media.manage.util.DownLoad;
import com.ssly.media.manage.util.JsonResult;
import com.ssly.media.manage.util.R;
import jdk.nashorn.internal.runtime.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Convert;
import java.io.File;
import java.sql.Timestamp;

import static java.lang.Thread.sleep;

@RestController
@RequestMapping("api/down-task")
public class DownTaskController {

    @Autowired
    private DownTaskRepository downTaskRepository;
    @Autowired
    private MediaProperties mediaProperties;
    @Autowired
    private SourceMediaService sourceMediaService;
    @Autowired
    private ConvertTaskService convertTaskService;

    @GetMapping("/{id}")
    public JsonResult show(Integer id) {
        return R.success();
    }

    @GetMapping
    public DataTablesOutput<DownTask> index(DataTablesInput input) {
        return downTaskRepository.findAll(input);
    }

    @PutMapping
    public JsonResult update() {
        return R.success();
    }

    @PostMapping
    public JsonResult create(DownTask downTask,@RequestParam(required = false) String transcoding) {

        downTask.setCreateTime(new Timestamp(System.currentTimeMillis()));
        DownTask saveDownTask = downTaskRepository.save(downTask);


        System.out.println(downTask);
        String downUrl = downTask.getDownUrl();
        try {
            DownLoad downLoad = new DownLoad(downUrl, mediaProperties.getSourceDir(), 4);
            downLoad.start();
            saveDownTask.setName(downLoad.getFileName());
            saveDownTask.setStatus(1);
            new Thread(() -> {
                while (true){
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    int curLength = downLoad.getCurLength();
                    int connectionLength = downLoad.getConnectionLength();
                    float progress = (float) (curLength * 100.0 / connectionLength);
                    saveDownTask.setProgress(progress);
                    downTaskRepository.save(saveDownTask);
                    //下载完成
                    if (curLength==connectionLength){
                        saveDownTask.setStatus(3);
                        downTask.setCompleteTime(new Timestamp(System.currentTimeMillis()));
                        downTaskRepository.save(saveDownTask);

                        File downFile = downLoad.getDownFile();
                        String fileName = downLoad.getFileName();
                        SourceMedia sourceMedia = sourceMediaService.create(downFile,fileName);

                        if (null!=transcoding&&!transcoding.isEmpty()){
                            ConvertTask convertTask=new ConvertTask();
                            convertTask.setSourceMediaId(sourceMedia.getId());
                            convertTaskService.create(convertTask);
                        }
                        System.out.println(sourceMedia+"\n创建成功");
                        return;
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("提交任务失败");
        }
        return R.success("提交任务成功");
    }

    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable Integer id) {
        downTaskRepository.deleteById(id);
        return R.success("删除成功");
    }

}
